import json
import os

CONFIG_FILE = 'config.json'

# Default configuration settings
DEFAULT_CONFIG = {
    'wifi': {
        'ssid': '',
        'password': ''
    },
    'ntp': {
        'servers': ['pool.ntp.org', 'ntp.aliyun.com', 'time.apple.com'],
        'max_retries': 2,
        'retry_interval': 2
    },
    'settings': {
        'timezone_offset': 8,  # UTC+8
        'log_level': 'info'
    }
}

def load_config():
    """
    Load configuration from file. If file doesn't exist or has errors,
    return default configuration.
    """
    try:
        if CONFIG_FILE in os.listdir():
            with open(CONFIG_FILE, 'r') as f:
                config = json.load(f)
            # Merge with default config to ensure all fields exist
            return merge_configs(DEFAULT_CONFIG, config)
        else:
            print(f"Config file {CONFIG_FILE} not found, using default configuration")
            return DEFAULT_CONFIG.copy()
    except Exception as e:
        print(f"Error loading config: {e}")
        return DEFAULT_CONFIG.copy()

def save_config(config):
    """
    Save configuration to file.
    """
    try:
        with open(CONFIG_FILE, 'w') as f:
            json.dump(config, f)
        print(f"Configuration saved to {CONFIG_FILE}")
        return True
    except Exception as e:
        print(f"Error saving config: {e}")
        return False

def set_wifi_config(ssid, password):
    """
    Update WiFi configuration and save to file.
    """
    config = load_config()
    config['wifi']['ssid'] = ssid
    config['wifi']['password'] = password
    return save_config(config)

def get_wifi_config():
    """
    Get WiFi configuration.
    """
    config = load_config()
    return config['wifi']

def update_config_section(section, data):
    """
    Update a specific section of the configuration.
    """
    config = load_config()
    if section in config:
        config[section].update(data)
        return save_config(config)
    else:
        print(f"Section '{section}' not found in configuration")
        return False

def merge_configs(default, user):
    """
    Deep merge two configuration dictionaries, with user values taking precedence.
    """
    if not isinstance(user, dict):
        return default
    
    result = default.copy()
    for key, value in user.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_configs(result[key], value)
        else:
            result[key] = value
    return result

def delete_config():
    """
    Delete the configuration file.
    """
    try:
        if CONFIG_FILE in os.listdir():
            os.remove(CONFIG_FILE)
            print(f"Configuration file {CONFIG_FILE} deleted")
            return True
        else:
            print(f"Configuration file {CONFIG_FILE} not found")
            return False
    except Exception as e:
        print(f"Error deleting config file: {e}")
        return False

def show_config():
    """
    Display the current configuration (hiding sensitive information).
    """
    config = load_config()
    # Create a copy to avoid modifying the original
    display_config = json.loads(json.dumps(config))
    # Hide password
    if 'wifi' in display_config and 'password' in display_config['wifi']:
        if display_config['wifi']['password']:
            display_config['wifi']['password'] = '********'
    print("Current configuration:")
    print(json.dumps(display_config))  # Removed indent parameter for MicroPython compatibility

# Example usage
if __name__ == '__main__':
    # Show current config
    show_config()
    
    # Example: Set WiFi config
    # set_wifi_config('your_ssid', 'your_password')
    
    # Example: Update NTP servers
    # update_config_section('ntp', {'servers': ['time1.google.com', 'time2.google.com']})
    
    # Example: Delete config
    # delete_config()